package com.topisv.tms.service.work.prepkg;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang.StringUtils;
import org.hibernate.ejb.criteria.predicate.ComparisonPredicate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.topisv.tms.entity.work.prepkg.PrepkgPkgItem;
import com.topisv.tms.entity.work.prepkg.PrepkgPkgTask;
import com.topisv.tms.entity.work.prepkg.PrepkgPlan;
import com.topisv.tms.entity.work.prepkg.PrepkgUpItem;
import com.topisv.tms.entity.work.prepkg.PrepkgUpTask;
import com.topisv.tms.repository.work.prepkg.PrepkgPkgItemDao;
import com.topisv.tms.repository.work.prepkg.PrepkgPkgTaskDao;
import com.topisv.tms.repository.work.prepkg.PrepkgPlanDao;
import com.topisv.tms.repository.work.prepkg.PrepkgUpItemDao;
import com.topisv.tms.repository.work.prepkg.PrepkgUpTaskDao;
import com.topisv.tms.utils.rule.TMSTransportRule;

/**
 * 包装任务（预包装流程）_service
 * @author ch
 */
@Component
@Transactional(readOnly = true)
public class PrepkgPkgTaskService {

	@Autowired
	private PrepkgPkgTaskDao prepkgPkgTaskDao;
	@Autowired
	private PrepkgPlanDao prepkgPlanDao;
	@Autowired
	private PrepkgUpTaskDao prepkgUpTaskDao;
	@Autowired
	private PrepkgPkgItemDao prepkgPkgItemDao;
	@Autowired
	private PrepkgUpItemDao prepkgUpItemDao;
	
	/**
	 * 查找任务
	 * @param param 查询参数
	 * @return
	 */
	public List<PrepkgPkgTask> loadTaskByParam(Map<String, Object> param) {
		Specification<PrepkgPkgTask> spec = getWhereClause(param);
		List<PrepkgPkgTask> taskList = this.prepkgPkgTaskDao.findAll(spec);
		return taskList;
	}
	
	/**
	 * 查询条件封装
	 * @param param
	 * @return
	 */
	private Specification<PrepkgPkgTask> getWhereClause(final Map<String, Object> param) {
		return new Specification<PrepkgPkgTask>(){
			@Override
		    public Predicate toPredicate(Root<PrepkgPkgTask> r, CriteriaQuery<?> q, CriteriaBuilder cb) {
		      Predicate pre = cb.conjunction();
		      
		      //customerCodes
		      String customerCodes=(String) param.get("customerCodes");
		      if(StringUtils.isNotBlank(customerCodes)) {
		    	  String[] customerCodeSplit = customerCodes.split(":");
				  ComparisonPredicate[] tempCustomerCode = new ComparisonPredicate[customerCodeSplit.length];
				  int i = 0;
				  for (String _customerCode : customerCodeSplit) {
					 tempCustomerCode[i] = (ComparisonPredicate) cb.equal(r.get("customerCode"), _customerCode);
					 i++;
				  }
				  pre.getExpressions().add(cb.or(tempCustomerCode));
		      }
			  
		      //areagroups
		      String areagroups=(String) param.get("areagroups");
		      if(StringUtils.isNotBlank(areagroups)) {
		    	  String[] areagroupSplit = areagroups.split(":");
				  ComparisonPredicate[] areagroupArray = new ComparisonPredicate[areagroupSplit.length];
				  int j = 0;
				  for (String _areagroup : areagroupSplit) {
						areagroupArray[j] = (ComparisonPredicate) cb.equal(r.get("warehouseCode"), _areagroup);
						j++;
				  }
				  pre.getExpressions().add(cb.or(areagroupArray));
			  }
		      
		      Date fromDate= (Date) param.get("fromDate");
		      if (fromDate != null) {
		        pre.getExpressions().add(cb.greaterThanOrEqualTo(r.<Date>get("createTime"), fromDate));
		      }
		      
		      Date toDate= (Date) param.get("toDate");
		      if (toDate != null) {
		        pre.getExpressions().add(cb.lessThanOrEqualTo(r.<Date>get("createTime"), toDate));
		      }
		      
		      String status=(String) param.get("status"); 
		      if(StringUtils.isNotBlank(status)){
		    	  if(status.equals("myTask")){ //我的包装任务
		    		  pre.getExpressions().add(cb.or(
		    				  cb.equal(r.get("status"),"token"),
		    				  cb.equal(r.get("status"),"doing")
		    				  ));
		    	  }
		    	  else{
		    		  pre.getExpressions().add(cb.equal(r.get("status"),status)); 
		    	  }
			  }
		      
		      String workerUuid=(String) param.get("workerUuid");
		      if(StringUtils.isNotBlank(workerUuid)){
					pre.getExpressions().add(cb.equal(r.get("workerUuid"),workerUuid));
			  }	
		      
		      return pre;
		    }
		  };
       }

	/**
	 * 领取任务
	 * @param taskId 任务ID
	 * @param userId 任务执行人
	 * @throws Exception 
	 */
	@Transactional(readOnly = false,rollbackFor=Exception.class)
	public void takeTask(Long taskId, String jobuuid) throws Exception{
		
		try {
			
			PrepkgPkgTask task=this.prepkgPkgTaskDao.findOne(taskId);
			if(!"undo".equals(task.getStatus())){
				throw new Exception("任务已经被领取");
			}
			
			//修改包装任务状态
			task.setWorkerUuid(jobuuid);
			task.setStatus("token"); 
			this.prepkgPkgTaskDao.save(task);
			
			
			//修改出库单状态
			PrepkgPlan plan=this.prepkgPlanDao.loadByPlanCode(task.getPlanCode());
			plan.setStatus("tokePkgTask"); //tokePkgTask:领取包装任务
			this.prepkgPlanDao.save(plan);
		
		} catch (Exception e) {
			
			throw e;
		}
		
	}

	/**
	 * 查询任务
	 * @param taskId
	 * @return
	 */
	public PrepkgPkgTask loadTaskById(Long taskId) {
		PrepkgPkgTask task=this.prepkgPkgTaskDao.findOne(taskId);
		return task;
	}

	/**
	 * 完成包装任务
	 * @param taskId
	 * @throws Exception 
	 */
	@Transactional(readOnly = false,rollbackFor=Exception.class)
	public void completeTask(Long taskId) throws Exception {
		try {
			
			//修改包装任务状态
			PrepkgPkgTask task=this.prepkgPkgTaskDao.findOne(taskId);
			task.setStatus("finish");
			this.prepkgPkgTaskDao.save(task);
			
			//修改计划状态
			PrepkgPlan plan=this.prepkgPlanDao.loadByPlanCode(task.getPlanCode());
			plan.setStatus("cmpPkgTask"); //状态 （cmpPkgTask:完成包装任务 )
			this.prepkgPlanDao.save(plan);
			
			//创建上架任务
			Date now=new Date();
			PrepkgUpTask upTask=new PrepkgUpTask();
			upTask.setCreateTime(now);
			upTask.setCustomerCode(plan.getCustomerCode());
			upTask.setGoodsNum(plan.getGoodsNum());
			upTask.setPlanCode(plan.getPlanCode());
			upTask.setSkuNum(plan.getSkuNum());
			upTask.setTaskCode(TMSTransportRule.generateUpPreTaskCode());
			upTask.setStatus("undo");
			upTask.setWarehouseCode(plan.getWarehouseCode());
			this.prepkgUpTaskDao.save(upTask);
			
			//创建上架任务明细
			List<PrepkgPkgItem> pkgItemList=this.prepkgPkgItemDao.loadByPlanCode(plan.getPlanCode());
			for (PrepkgPkgItem pkgItem : pkgItemList) {
				PrepkgUpItem upItem=new PrepkgUpItem();
				upItem.setCustomerCode(plan.getCustomerCode());
				upItem.setNum(pkgItem.getNum());
				upItem.setPlanCode(plan.getPlanCode());
				upItem.setSku(pkgItem.getSku());
				upItem.setStatus("unupped");
				upItem.setTaskCode(upTask.getTaskCode());
				upItem.setUpNum(0);
				upItem.setWarehouseCode(plan.getWarehouseCode());
				this.prepkgUpItemDao.save(upItem);
			}
			
			
		} catch (Exception e) {
			
			throw e;
		}
	}

}